package com.daily.tools.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.daily.tools.bean.WriteModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class EasyExcelController {

    @GetMapping("download")
    public void cooperation(HttpServletResponse response) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        String fileName = new String(("UserInfo " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), StandardCharsets.UTF_8);

        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName("第一个sheet");

        writer.write0(getListString(), sheet);

        response.setContentType( "multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" +fileName+ ".xlsx");

        writer.finish();
        out.flush();

    }

    private List<List<String>> getListString() {
        List<List<String>> rows = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            List<String> row = new ArrayList<>();
            row.add("asdasdsad");
            row.add("aaaaaaaa");
            row.add("bbbbbbbb");
            rows.add(row);
        }
        return rows;
    }

}
